package com.zeny.online.util;

import org.springframework.util.Base64Utils;
import org.springframework.util.ClassUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @ClassName FileUtil
 * @Description base64转字节数组
 * @Author zeny
 */
public class FileUtil {

    public static byte[] base64ToFile(String base64Data)  throws Exception {
        String dataPrix = "";
        String data = "";

        if(base64Data == null || "".equals(base64Data)){
            return null;
        }else{
            String [] d = base64Data.split("base64,");
            if(d != null && d.length == 2){
                dataPrix = d[0];
                data = d[1];
            }else{
                return null;
            }
        }

        // 因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        return bs;
    }

    public static byte[] getBytes(String filePath)  {
        FileInputStream in = null;
        ByteArrayOutputStream outStream = null;
        try {
            in = new FileInputStream(filePath);
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] bytes = outStream.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
